import { preview } from '@/services/develop/generator';
import { Breadcrumb, Divider, Layout, Tree } from 'antd';
import type { ReactNode } from 'react';
import { useEffect, useState } from 'react';
import Script from '../script/Script';
import {
  DownOutlined,
  FileTextOutlined,
  FolderOpenOutlined,
  FolderOutlined,
  HomeOutlined,
} from '@ant-design/icons';

const { Sider, Header, Content } = Layout;

type PreviewProps = {
  modelId: string | string[];
};

function processTree(tree: any) {
  // 遍历树形结构数据
  for (let i = 0; i < tree.children.length; i++) {
    const child = tree.children[i];

    // 如果当前节点的children长度为1且children唯一元素的leaf为false
    if (
      tree.children.length === 1 &&
      !child.leaf &&
      child.name != 'src' &&
      tree.name != 'src' &&
      tree.name != 'main' &&
      tree.name != 'java' &&
      tree.name != 'resources'
    ) {
      // 将children唯一元素的children设置为当前节点的children
      tree.children = child.children;

      // 当前节点的name设置为当前节点的name与children唯一元素的name的拼接
      tree.name = tree.name + '.' + child.name;

      // 继续处理当前节点的children
      processTree(tree);
    } else {
      // 如果不符合条件，继续递归处理当前节点的children
      processTree(child);
    }
  }
}

const Preview: React.FC<PreviewProps> = (props) => {
  const [files, setFiles] = useState([]);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [currentFile, setCurrentFile] = useState<any>({});

  const collectKeys = (keys: string[], nodes: string | any[]) => {
    for (let i = 0; i < nodes.length; i++) {
      keys.push(nodes[i].key);
      collectKeys(keys, nodes[i].children);
    }
    return keys;
  };

  const defaultFile = (nodes: any) => {
    for (let i = 0; i < nodes.length; i++) {
      let node = nodes[i];
      if (node.leaf) {
        return node;
      }

      node = defaultFile(node.children);
      if (node != null) {
        return node;
      }
    }

    return null;
  };

  useEffect(() => {
    preview(props.modelId)
      .then((res) => {
        const data = res.data;

        for (let i = 0; i < data.length; i++) {
          processTree(data[i]);
        }

        const keys = collectKeys([], data);
        setFiles(data);
        setExpandedKeys(keys);

        const node = defaultFile(data);
        setCurrentFile(node);
      })
      .catch((e) => {
        console.error(e);
        setCurrentFile({});
      });
  }, [props.modelId]);

  return (
    <Layout hasSider style={{ height: 800 }}>
      <Sider width={'400px'} style={{ background: '#fff', paddingRight: '18px', flexGrow: 1 }}>
        <Tree
          icon={(value: any) => {
            return value.leaf ? (
              <FileTextOutlined style={{ color: 'var(--ant-primary-color)' }} />
            ) : (
              <FolderOutlined />
            );
          }}
          switcherIcon={<DownOutlined />}
          rootStyle={{
            height: '100%',
            width: '400px',
            alignSelf: 'stretch',
            overflow: 'auto',
          }}
          expandedKeys={expandedKeys}
          selectedKeys={currentFile && currentFile.key && [currentFile.key]}
          onExpand={(keys) => {
            setExpandedKeys(keys.map((key) => key.toString()));
          }}
          showIcon
          showLine
          treeData={files}
          fieldNames={{
            title: 'name',
          }}
          onSelect={(_, e: { node: { content: string; icon: ReactNode } }) => {
            const content = e.node.content;
            if (content == null) {
              return;
            }
            setCurrentFile(e.node);
          }}
        />
      </Sider>
      <Layout style={{ background: '#fff' }}>
        <Header style={{ textAlign: 'center', background: '#Fff', paddingLeft: 0 }}>
          <Breadcrumb>
            <Breadcrumb.Item>
              <HomeOutlined />
            </Breadcrumb.Item>
            {currentFile?.path
              ?.replaceAll('//', '/')
              .split('/')
              .map((item: string) => {
                return <Breadcrumb.Item key={item}>{item}</Breadcrumb.Item>;
              })}
          </Breadcrumb>
        </Header>
        <Content>
          <Script
            style={{
              height: '100%',
              alignSelf: 'stretch',
              overflow: 'auto',
            }}
            type="java"
            code={(currentFile && currentFile.content) || ''}
          />
        </Content>
      </Layout>
    </Layout>
  );
};

export default Preview;
